/**
 * @Function 部门数据归集统计Controller
 * @ProjectName credit-data-platform
 * @PackageName com.py.credit.controller
 * @FileName AchievementCountController.java
 * @Date 2018年5月14日下午2:47:13
 * @Author Min DongXv
 * @Copyright (c) 2018, 金电联行 All Rights Reserved.
 */
package com.py.credit.controller;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.AchievementCountFieldEnum;
import com.py.credit.entity.enums.AchievementDetailsFieldEnum;
import com.py.credit.service.AchievementService;
import com.py.credit.service.RemoteBaseService;
import com.py.credit.utils.ExcelUtil;
import com.py.credit.utils.MapCache;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;

/**
 * @Function 部门数据归集统计Controller
 * @ClassName AchievementController
 * @Date 11:06 18/7/20
 * @Author Yaos
 */
@RestController
@RequestMapping(value = "/achievement")
public class AchievementController extends BaseController {
	// 归集部门统计概述
	private static final String ACHIEVEMENT_COUNT_ID = "achievement_count";
	// 归集部门统计详情
	private static final String ACHIEVEMENT_DETAILS_ID = "achievement_details";

	@Autowired
	private AchievementService achievementService;

	@Autowired
	private RemoteBaseService remoteBaseService;

	// 获取统计概述
	@RequestMapping(value = "/getCountColums.json")
	public RestServiceResult<List<OptionalColumn>> getCountColums() {
		return new RestServiceResult<List<OptionalColumn>>(AchievementCountFieldEnum.getOptionalColumns());
	}

	// 获取统计详情
	@RequestMapping(value = "/getDetailslColums.json")
	public RestServiceResult<List<OptionalColumn>> getDetailslColums() {
		return new RestServiceResult<List<OptionalColumn>>(AchievementDetailsFieldEnum.getOptionalColumns());
	}

	@RequestMapping(value = "/getAdvancedConditionColumns.json")
	public RestServiceResult<List<OptionalColumn>> getAdvancedConditionColumns() {
		return new RestServiceResult<List<OptionalColumn>>(AchievementCountFieldEnum.getAdvancedConditionColumns());
	}

	@RequestMapping(value = "/addShowColunms.json")
	public RestServiceResult<String> addShowColunms(@RequestParam(value = "columns", required = true) String[] columns,
			HttpServletRequest request) {
		RestServiceResult<String> result = new RestServiceResult<String>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("AchievementController#addShowColunms", "未获取到当前用户信息！");
				return result;
			}
			String column = StringUtils.join(columns, ",");
			MapCache.set(userInfo.getId() + "_" + ACHIEVEMENT_COUNT_ID, StringUtils.split(column, ","));
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		return new RestServiceResult<String>();
	}

	/**
	 * @api {get} /achievement/getAchievementCount.json 归集部门绩效概述页
	 * @apiName getAchievementCount
	 * @apiVersion 0.0.1
	 * @apiGroup 数据管理
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} dateRange 期数
	 * @apiSuccess {String} deptName 部门
	 * @apiSuccess {String} resourceTitle 数据目录
	 * @apiSuccess {String} frequency 报送周期 S:实时 D:每日 W:每周 M:每月 Q:每季度 Y:每年
	 * @apiSuccess {String} isAchieve 绩效完成情况 Y:是 N:否 R:进行中 Z:暂不统计
	 * @apiSuccess {Integer} scount 报送数据
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":1,"data":[{"dateRange":"201808","deptName":"信用中心","resourceTitle":"欠缴水费信息","frequency":"D","isAchieve":"Y","scount":10}]}
	 */
	@RequestMapping(value = "/getAchievementCount.json")
	public RestServiceResult<List<Map<String, Object>>> getAchievementCount(
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
			HttpServletRequest request) {
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("AchievementController#getAchievementCount", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		String[] configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + ACHIEVEMENT_COUNT_ID);
		List<String> showColumns = (configColumns == null || configColumns.length == 0)
				? AchievementCountFieldEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
		List<Map<String, Object>> data;
		try {
			data = achievementService.selectAchievementCountByConditionForPage(userInfo, showColumns, null, condition,
					page);

			result.setData(data);
			result.setCount(page.getTotalCount());
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("归集部门绩效概述统计异常，请稍后再试！");
			ExceptionLogger.error("归集部门绩效概述统计查询异常！", e.getMessage(), e);
			return result;
		}
	}

	/**
	 * @api {get} /achievement/getAchievementDetails.json 归集部门绩效统计详情
	 * @apiName getAchievementDetails
	 * @apiVersion 0.0.1
	 * @apiGroup 数据管理
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} dateRange 期数
	 * @apiSuccess {String} resourceTitle 数据目录
	 * @apiSuccess {String} frequency 报送周期 S:实时 D:每日 W:每周 M:每月 Q:每季度 Y:每年
	 * @apiSuccess {String} isAchieve 绩效完成情况 Y:是 N:否 R:进行中 Z:暂不统计
	 * @apiSuccess {Integer} scount 报送数据
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":1,"data":[{"dateRange":"201808","resourceTitle":"欠缴水费信息","frequency":"D","isAchieve":"Y","scount":10}]}
	 */
	@RequestMapping(value = "/getAchievementDetails.json")
	public RestServiceResult<List<Map<String, Object>>> getAchievementDetails(
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition,
			@RequestParam(value = "dateRange", defaultValue = "", required = true) String dateRange, Page page,
			@RequestParam(value = "deptId", defaultValue = "", required = true) Integer udeptId,
			HttpServletRequest request) {
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
		String token = HttpServletHelper.getUserToken(request);
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("AchievementController#getAchievementDetails", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		// String[] configColumns = (String[]) MapCache.get(userInfo.getId() +
		// "_" +
		// ACHIEVEMENT_DETAILS_ID);
		// List<String> showColumns = (configColumns == null ||
		// configColumns.length ==
		// 0)
		// ? AchievementDetailsFieldEnum.getDefaultShowColumnEN()
		// : Arrays.asList(configColumns);
		List<String> showColumns = AchievementDetailsFieldEnum.getDefaultShowColumnEN();
		List<Map<String, Object>> data;
		try {
			data = achievementService.selectAchievementDetailsForPage(userInfo, showColumns, null, condition, dateRange,
					page, udeptId);
			if (!CollectionUtils.isEmpty(data)) {
				Set<Integer> userIds = new HashSet<Integer>(data.size());
				for (Map<String, Object> m : data) {
					if (null != m && m.containsKey("managerId") && null != m.get("managerId")) {
						userIds.add(Integer.parseInt(String.valueOf(m.get("managerId"))));
					}
				}
				// 填充用户名称
				remoteBaseService.matchUserName(data, result, token, userIds, "managerId", "lastOperatorName");
			}
			if (RestServiceResult.CODE_SUCCESS != result.getCode()) {
				return result;
			}
			result.setData(data);
			result.setCount(page.getTotalCount());
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("归集部门绩效统计异常，请稍后再试！");
			ExceptionLogger.error("归集部门绩效统计查询异常！", e.getMessage(), e);
			return result;
		}
	}

	// 填充部门信息
	private List<Map<String, Object>> dealAchievementData(List<Map<String, Object>> data,
			RestServiceResult<List<Map<String, Object>>> result, String token) {
		// 提取区域ID
		if (!CollectionUtils.isEmpty(data)) {
			// 获取当前用户的所有部门信息
			RestServiceResult<Map<String, String>> depts = remoteBaseService.getCurrentUserOfficesName(token);
			if (RestServiceResult.CODE_SUCCESS != depts.getCode()) {
				result.setCode(depts.getCode());
				result.setMsg(depts.getMsg());
				return data;
			}
			Map<String, String> deptInfo = depts.getData();
			// 填充部门名称
			for (Iterator<Map<String, Object>> it = data.listIterator(); it.hasNext();) {
				Map<String, Object> map = it.next();
				if (null != map) {
					String regionName = deptInfo.get(String.valueOf(map.get("deptId")));
					if (StringUtils.isNotEmpty(regionName)) {
						map.put("deptName", regionName);
					} else {
						map.put("deptName", "");
					}
				}
			}
		}
		return data;
	}

	/**
	 * @api {get} /achievement/dealAchievementCountData.do 归集部门绩效统计定时任务
	 * @apiName dealAchievementData
	 * @apiVersion 0.0.1
	 * @apiGroup 数据管理
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 */
	@RequestMapping("/dealAchievementCountData.do")
	public RestServiceResult<Object> dealAchievementData() {
		try {
			achievementService.dealAchievementData();
			return new RestServiceResult<Object>();
		} catch (Exception e) {
			RestServiceResult<Object> result = new RestServiceResult<Object>();
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("处理归集部门绩效统计任务异常！");
			ExceptionLogger.error("归集部门绩效统计定时任务AchievementController#dealAchievementData",
					"处理归集部门绩效统计任务异常！ERROR：" + e.getMessage(), e);
			return result;
		}
	}

	/**
	 * @api {get} /achievement/export.json 归集部门绩效统计导出
	 * @apiName exportData
	 * @apiVersion 0.0.1
	 * @apiGroup 数据管理
	 * @apiParam {String} condition
	 * @apiParam {String} showColumn 导出列的编码的数组
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} result
	 * @apiSuccessExample {json} 成功返回结果 {}
	 */
	@RequestMapping(value = "/export")
	public RestServiceResult<List<Map<String, Object>>> exportData(
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition,
			@RequestParam(value = "columnEN", defaultValue = "", required = true) String columnEN, Page page,
			HttpServletResponse response, HttpServletRequest request) {
		page.setLimit(1000);
		List<String> showColumns = JSONArray.parseArray(columnEN, String.class);
		List<OptionalColumn> optionalColumns = AchievementCountFieldEnum.getOptionalColumns();
		List<Map<String, Object>> data;
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("AchievementController#getAchievementCount", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		try {
			data = achievementService.selectAchievementCountByConditionForPage(userInfo, showColumns, null, condition,
					page);
			// 填充部门信息
			data = dealAchievementData(data, result, HttpServletHelper.getUserToken(request));
			if (RestServiceResult.CODE_SUCCESS != result.getCode()) {
				return result;
			}
			ExcelUtil.downloadExcel(response, data, "归集部门绩效统计", "归集部门绩效统计", showColumns, optionalColumns);
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("归集部门绩效统计导出异常，请稍后再试！");
			ExceptionLogger.error("归集部门绩效统计导出异常！", e.getMessage(), e);
			return result;
		}
	}
}
